package main;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JTextField;


/**
 * Calculator
 *
 * @author Joonas Vali
 */
public class Calculator {	
	public static String ARITHMETIC_EXCEPTION = "Arithmetic Error";
	public static String NUMBERFORMAT_EXCEPTION = "Syntax Error";
	private final StringBuilder input = new StringBuilder();
	private final JTextField GUIScreen;	
	
	public Calculator(JTextField screen){
		this.GUIScreen = screen;
	}
	
	public ActionListener getInputListener(final String operator){
		return new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent a) {
				if(input.toString().equals(ARITHMETIC_EXCEPTION)) clear();				
				input.append(operator);	
				updateGUIScreen();
			}			
		};
	}
	
	public ActionListener getResultListener(){
		return new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent a) {	
				String ans;
				try{
					ans = Expression.calculate(input.toString());
				} catch(ArithmeticException e){
					ans = ARITHMETIC_EXCEPTION;
				} catch(NumberFormatException e){
					ans = NUMBERFORMAT_EXCEPTION;
				}
				clear();					
				input.append(ans);
				updateGUIScreen();
			}			
		};
	}
	
	public ActionListener getClearListener(){
		return new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent a) {				
				input.delete(0, input.length());
				updateGUIScreen();
			}			
		};
	}
	
	public void clear(){
		input.delete(0, input.length());	
	}
	
	public String getInput(){
		return input.toString();
	}
	
	public void updateGUIScreen(){		
		GUIScreen.setText(input.length() > 0 ? input.toString(): "0");
	}
}
